#!/bin/bash

##-- Check if docker is installed --#
if [ -z "$(command -v docker)" ]; then
	echo '== Error: Docker binary is not found. Is docker installed?'; exit 56
fi
##-- Check if pgrok is installed when auto tunneling service is enabled --#
if [ "$DRONE_SERVER_HOST" == "AUTO" ] && [ "$TUNNELING_SERVICE" == "pgrok" ] && [ -z "$(command -v pgrok)" ]; then
	echo '== Error: pgrok binary is not found. Is pgrok installed?'; exit 38
fi
##-- Check if npm is installed when localtunnel is selected --#
if [ "$DRONE_SERVER_HOST" == "AUTO" ] && [ "$TUNNELING_SERVICE" == "localtunnel" ] && [ -z "$(command -v npx)" ]; then
	echo '== Error: npx binary is not found. Is npm installed?'; exit 48
fi
##-- Check if tunnelto is installed and api key when auto tunneling service is enabled --#
if [ "$DRONE_SERVER_HOST" == "AUTO" ] && [ "$TUNNELING_SERVICE" == "tunnelto" ]; then
	if [ -z "$(command -v tunnelto)" ]; then
		echo '== Error: tunnelto binary is not found. Is tunnelto installed?'; exit 73
	fi
	if [ -z "$TUNNELTO_API_KEY" ]; then
		echo '== Error: tunnelto API key is required. Please visit https://tunnelto.dev/ to get one for free and put it on config.sh in TUNNELTO_API_KEY.'; exit 17
	fi
fi

##-- Deal with configs --##
CURRDIR=$(realpath $(dirname $0))
if [ -f "$CURRDIR/config.sh" ]; then
	. "$CURRDIR/config.sh"
else
	echo '== config.sh not found, exiting...'; exit 23
fi
#-- Check if repo provider is ok --#
if [ -z "$REPO_PROVIDER" ]; then
	echo "== Error: config.sh is probably not updated. Please check the 'Troubleshooting' section on docs/config.md."; exit 63
elif [ "$REPO_PROVIDER" != "gitea" ] && [ "$REPO_PROVIDER" != "gogs" ]; then
	echo "== Error: Repo provider ${REPO_PROVIDER} not supported. Please change REPO_PROVIDER on config.sh to a supported one."; exit 39
fi

##-- Check if containers are already running from a previous start.sh run --#
if [ -f "${CURRDIR}/run/running_containers" ]; then
	read -e -p "Containers are running from previous session. Would you like to stop them first? [y/N] " choice
	if [[ "$choice" == [Yy]* ]]; then
		${CURRDIR}/stop.sh
		echo '== Stopped. Now continuing to start...'
	else
		echo "Cannot run what's already running! Exiting..."; exit 190
	fi
fi

##-- Deal with auto local tunneling, if needed --##
if [ "$DRONE_SERVER_HOST" = "AUTO" ]; then
	echo '== Creating localhost tunneling url automatically...'
	if [ "$TUNNELING_SERVICE" = "pgrok" ]; then
		setsid pgrok -subdomain="${TUNNELING_SERVICE_SUBDOMAIN}" 8090 2>/dev/null &
		# Store the pid to kill it later on stop.sh
		echo $! > "${CURRDIR}/run/tunneling_pid"
		export DRONE_SERVER_HOST="${TUNNELING_SERVICE_SUBDOMAIN}.ejemplo.me"
		echo "${DRONE_SERVER_PROTO}://${DRONE_SERVER_HOST}" > "${CURRDIR}/run/tunneling_url"
	elif [ "$TUNNELING_SERVICE" = "tunnelto" ]; then
		tunnelto set-auth --key "${TUNNELTO_API_KEY}"
		setsid tunnelto --subdomain "${TUNNELING_SERVICE_SUBDOMAIN}" --port 8090 2>/dev/null &
		# Store the pid to kill it later on stop.sh
		echo $! > "${CURRDIR}/run/tunneling_pid"
		export DRONE_SERVER_HOST="${TUNNELING_SERVICE_SUBDOMAIN}.tunnelto.dev"
		echo "${DRONE_SERVER_PROTO}://${DRONE_SERVER_HOST}" > "${CURRDIR}/run/tunneling_url"
	elif [ "$TUNNELING_SERVICE" = "localtunnel" ]; then
		mkdir -p /tmp/dronedocker/
		setsid npx lt --port 8090 > /tmp/dronedocker/autolt.output &
		# Store the pid to kill it later on stop.sh
		echo $! > "${CURRDIR}/run/tunneling_pid"
		sleep 5
		export DRONE_SERVER_HOST=$(grep -Po '(?i)https://\K(.*)' /tmp/dronedocker/autolt.output)
		echo "${DRONE_SERVER_PROTO}://${DRONE_SERVER_HOST}" > "${CURRDIR}/run/tunneling_url"
	fi
	DRONE_RPC_HOST="${DRONE_SERVER_HOST}"
	echo "Selecting url automatically as: ${DRONE_SERVER_PROTO}://${DRONE_SERVER_HOST}"
fi

##-- Create main server --##
export REPO_SERVER_HOST=$(echo "${REPO_SERVER}" | sed -e 's|^[^/]*//||' -e 's|/.*$||')
export DRONE_ALLOWED_USERS="${REPO_USERNAME}@${REPO_SERVER_HOST}"

CMD="docker run \
	--volume=/var/run/docker.sock:/var/run/docker.sock \
	--volume='${CURRDIR}':/data"

# Gitea
if [ "$REPO_PROVIDER" = "gitea" ]; then
	CMD="${CMD} \
		--env=DRONE_GITEA_SERVER='${REPO_SERVER}' \
		--env=DRONE_GITEA_CLIENT_ID='${REPO_CLIENT_ID}' \
		--env=DRONE_GITEA_CLIENT_SECRET='${REPO_CLIENT_SECRET}'"
# Gogs
elif [ "$REPO_PROVIDER" = "gogs" ]; then
	CMD="${CMD} \
		--env=DRONE_GOGS_SERVER=${REPO_SERVER}"
fi

CMD="${CMD} \
	--env=DRONE_RUNNER_CAPACITY=2 \
	--env=DRONE_SERVER_HOST=${DRONE_SERVER_HOST} \
	--env=DRONE_RPC_SECRET=${DRONE_RPC_SECRET} \
	--env=DRONE_SERVER_PROTO=${DRONE_SERVER_PROTO} \
	--env=DRONE_TLS_AUTOCERT=true \
	--env=DRONE_USER_CREATE=username:${REPO_USERNAME},admin:true \
	--publish=8090:80 \
	--publish=443:443 \
	--restart=always \
	--detach=true \
	--name=${DOCKER_MAIN_NAME} \
	drone/drone:latest"

eval "${CMD}"
echo "${DOCKER_MAIN_NAME}" >> "${CURRDIR}/run/running_containers"

##-- Create runner agent --##
sudo docker run -d \
	--volume=/var/run/docker.sock:/var/run/docker.sock \
	--env=DRONE_RPC_PROTO=${DRONE_RPC_PROTO} \
	--env=DRONE_RPC_HOST=${DRONE_RPC_HOST} \
	--env=DRONE_RPC_SECRET=${DRONE_RPC_SECRET} \
	--env=DRONE_RUNNER_CAPACITY=2 \
	--env=DRONE_RUNNER_NAME=${DOCKER_RUNNER_NAME} \
	--publish=3000:3000 \
	--restart=always \
	--name=${DOCKER_RUNNER_NAME} \
	drone/drone-runner-docker:latest
echo "${DOCKER_RUNNER_NAME}" >> "${CURRDIR}/run/running_containers"

#-- Setup message --#
echo "== Docker images created"
echo "== Change 'Redirect URL' on your OAuth2 settings to: ${DRONE_SERVER_PROTO}://${DRONE_SERVER_HOST}/login"
echo "== Then access the above url to continue"

echo '== Finished.'
